package cn.lbaicai.aop;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import cn.lbaicai.common.MethodLog;

@Component
@Aspect
public class AspectAdvice {
	public Logger log = Logger.getLogger(AspectAdvice.class);
	@Pointcut("@annotation(cn.lbaicai.common.MethodLog)")  
	public void anyMethod(){}
	@Around("anyMethod()")
	public Object around(ProceedingJoinPoint point) throws Throwable{
		log.info("around--->");
		return point.proceed();
	}
	@After("anyMethod()")
	public void after(JoinPoint jp){
		log.info(jp.getSignature().getName());
		try {
			getMessage(jp);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log.info("target--->"+jp.getTarget());
		log.info("args--->"+jp.getArgs());
		log.info("this--->"+jp.getThis());
		log.info("after....");
	}
	@Before("anyMethod()")
	public void before(){
		log.info("before....");
	}
	public Map<String, Object>  getMessage(JoinPoint point) throws ClassNotFoundException{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String targeName = point.getTarget().getClass().getName();
		String methodName = point.getSignature().getName();
		Object[] arguments = point.getArgs();
		Class targetClass = Class.forName(targeName);
		Method[] methods = targetClass.getMethods();
		for(Method method:methods){
			if(method.getName().equals(methodName)){
				Class[] clazzs = method.getParameterTypes();
				if(clazzs.length == arguments.length){
					resultMap.put("remark", method.getAnnotation(MethodLog.class).remark());
					break;
				}
			}
		}
		return resultMap;
	}
	//public 
}
